package org.nepu.scr.template;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.ufs.entity.UfsFile;
import org.lboot.ufs.service.UfsCtl;
import org.nepu.scr.template.params.ExportTemplateCreateParams;
import org.nepu.scr.template.params.ExportTemplateQueryParams;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("design/export")
@AllArgsConstructor
@Api(tags = "导出模板管理")
public class ExportTemplateController {
    UfsCtl ufsCtl;

    ExportTemplateService templateService;
    @PostMapping("templates")
    @ApiOperation(value = "导出模板新增")
    public ResponseDTO<Object> exportTemplateAdd(ExportTemplateCreateParams params){
        MultipartFile file = params.getFile();
        UfsFile ufsFile = ufsCtl.uploadFile(file, "导出模板/");
        ExportTemplate template = new ExportTemplate();
        template.setTemplateFileId(ufsFile.getId());
        template.setTemplateDesc(params.getTemplateDesc());
        template.setTemplateVersion(params.getTemplateVersion());
        return ResponseDTO.succData(
                templateService.saveOne(template)
        );
    }

    @GetMapping("templates")
    @ApiOperation(value = "导出模板列表")
    public ResponseDTO<Object> exportTemplateList(ExportTemplateQueryParams params){
        if (!Validator.isEmpty(params)){
            ExportTemplate data = new ExportTemplate();
            BeanUtil.copyProperties(params, data, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            Example<ExportTemplate> example = Example.of(data);
            return ResponseDTO.succData(
                    templateService.getAll(example)
            );
        }else{
            List<ExportTemplate> templates = templateService.getAll();
            return ResponseDTO.succData(
                    templates);
        }
    }

    @DeleteMapping("templates/{id}")
    @ApiOperation(value = "导出模板删除")
    public ResponseDTO<Object> exportTemplateDelete(@PathVariable("id") Long id){
        ExportTemplate template = templateService.getOneUnwrap(id);
        ufsCtl.deleteFile(template.getTemplateFileId());
        templateService.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }

}
